package thread;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * Creared with IntelliJ IDEA.
 * Description:自己实现的线程池
 * User:yxd
 * Date:2022-03-29
 * Time:17:58
 */
class MyThreadPool{
    //描述任务,使用runnable
    //管理任务使用BlockingQueue
    private BlockingQueue<Runnable> queue = new LinkedBlockingQueue<>();
    //描述一个线程,工作线程的功能就是从任务队列里面获得任务并执行
    static class Worker extends Thread{
        //当线程池有若干个Worker线程,这些线程内部都持有了上述的任务队列
        private BlockingQueue<Runnable> queue = null;
        //构造方法传入当前queue
        public Worker(BlockingQueue<Runnable> queue) {
            this.queue = queue;//获取到队列的实例
        }

        @Override
        public void run() {
            //需要获得到阻塞队列里面的任务
            while (true){
                try {
                    Runnable runnable = queue.take();//能获得到就是可以执行,是空的话就直接阻塞了
                    //执行
                    runnable.run();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }


    }
    //4.创建一个数据结构来组织若干个线程
    private List<Worker> workers = new ArrayList<>();
    //传入这些worker
    public MyThreadPool(int n){
        Worker worker = new Worker(queue);
        worker.start();//启动
        workers.add(worker);//将这些任务放进数组
    }
    //5.创建submit方法允许程序员来放任务到线程池中
    public void submit(Runnable runnable){
        try {
            queue.put(runnable);//将任务放进去
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
public class Demo26 {
    public static void main(String[] args) {
        MyThreadPool pool = new MyThreadPool(10);
        for (int i = 0;i < 100;i ++){
            pool.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println("hello threadPool");
                }
            });
        }
    }
}
